/*

var zhong = ['f','c','g','a','d','b','e'];
var hou = ['f','g','c','d','e','b','a'];

function Node(value) {
	this.value = value;
	this.left = null;
	this.right = null;
}
/!*
* 找到根节点在中序遍历中的位置
* 后序遍历的（左 右）子树
* 中序遍历的（左 右）子树
* 根据左子树的后序和中序 还原左子树并赋值给root.left
* 根据右子树的后序和中序 还原左子树并赋值给root.right
* *!/


function f1(zhong,hou) {
	if(hou === null || zhong === null ||
		hou.length === 0 || zhong.length === 0 ||
		hou.length !== zhong.length) return null;

	var root = new Node(hou[hou.length - 1]);
	var index= zhong.indexOf(root.value) //获取根节点的索引
	var houLeft = hou.slice(0, index);
	var houRight = hou.slice(index, hou.length- 1) //
	var zhongLeft = zhong.slice(0, index);
	var zhongRight = zhong.slice(index+1, zhong.length);

	root.left = f1(zhongLeft,houLeft);
	root.right = f1(zhongRight,houRight);
	return  root
}

var root = f1(zhong,hou)
console.log(root.left)
console.log(root.right)*/




var zhong = ['f','c','g','a','d','b','e'];
var hou = ['f','g','c','d','e','b','a'];

function Node(value) {
	this.value = value;
	this.left = null;
	this.right = null;
}

function f1(zhong, hou) {
	if(zhong === null || hou === null || zhong.length === 0 || hou.length === 0 || zhong.length !== hou.length) return null;

	var root = new Node(hou[hou.length - 1]);       //根据后序遍历 找出最后一个为根节点
	var index = zhong.indexOf(root.value);          //获取中序遍历中 根节点的索引

	var zhongLeft = zhong.slice(0, index);  //'f','c','g'    0 1 2
	var zhongRight = zhong.slice(index + 1, zhong.length);  //'d','b','e'    4 5 6

	var houLeft = hou.slice(0, index);  //'f','g','c'   0 1 2
	var houRight = hou.slice(index, hou.length - 1); //'d','e','b'   3 4 5

	root.left = f1(zhongLeft,houLeft);          //左子树赋值给root.left
	root.right = f1(zhongRight, houRight);      //右子树赋值给root.right
	return root

}

var root = f1(zhong, hou);
console.log(root.left);
console.log(root.right)

